package com.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.servlet.M;

import hyl.core.MyFun;
import hyl.ext.base.MySession;
import hyl.ext.base.SessionFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 防止提交过快,连续提交 上一次未处理完成又一次提交
 * @author 37798955@qq.com
 *
 */
public class MyInterceptor implements HandlerInterceptor {
	private final static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		// 停用session
		// logger.info(req.getServletPath());//半路径 /getVerifyCode&t=1547715903259
		// logger.info(req.getContextPath());//根路径 hmjsp
		logger.info(req.getRequestURL().toString()); // 全路径 http://localhost:8080/hmjsp/getVerifyCode&t=1547715903259
		SessionFactory.getInstance();
		// System.out.println("拦截1:"+req.getRequestURL().toString());
		// 如果当前用户的tokenid 存在,如果提交码 处于处理中,那么不允许提交
		MySession tk = SessionFactory.getSession(req, res);
		//MyFun.printJson(tk);
		tk.setLang(1);
		tk.msg.setCode(0, null);
		// 防止重复提交
		if (tk.state[1] != MySession.REQ_无任务) {
			tk.msg.setCode(0, M.MSG_频繁);
			// System.out.println("拦截1，36");
			return false;
		}
		// 过滤非法ip
		// if (BlackUser.getInstance().containIP(tk.getIp())) { 
		// tk.msg.setCode(0, M.MSG_阻拦); 
		// Response.forwardOrJson(req, res, M.URL_login,tk.msg); 
		// return false; 
		tk.state[1] = MySession.REQ_受理中;
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		// Token tk =(Token) request.getAttribute(Response.ATTR_TOKEN);
		// tk.state_wok[0]=Token.STATE0_已处理;
	}

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex)
			throws Exception {
		// logger.info("进入 afterCompletion 方法..." + request.getRequestURL().toString() +
		// "," + request.getRequestURI());
		HttpSession sess=req.getSession(false);
		if (sess==null) {
			return;
		}	
		MySession se =  SessionFactory.getSession(req);
		if (se==null) {
			return;
		}
		se.refresh任务状态();// 每次提交设为1, 截止到处理结束设置为0 ,如果点击太快,自动阻拦
		//logger.info(JSON.toJSONString(se));// 监控可以关闭
	}

}
